﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace EzyThirdLogic.ExtensionMethods
{

    public static class BitArrayExtensions
    {
        /// <summary>
        /// Returns the index of the first bit that is set to true that occurs on or after the specified starting index.
        /// If no such bit exists then -1 is returned
        /// </summary>
        /// <param name="bitArray"></param>
        /// <param name="fromIndex"></param>
        /// <returns></returns>
        public static int NextSetBit(this BitArray bitArray, int fromIndex)
        {
            for (int i = fromIndex; i < bitArray.Length; i++)
            {
                if (bitArray.Get(i) == true)
                    return i;
            }
            return -1;
        }

        /// <summary>
        /// Returns the number of bits set to true in this BitSet.
        /// </summary>
        /// <param name="bitArray"></param>
        /// <returns></returns>
        public static int Cardinality(this BitArray bitArray)
        {
            var count = 0;
            foreach (bool bit in bitArray)
            {
                if (bit == true)
                    count++;
            }
            return count;
        }

        public static int LogicalSize(this BitArray bitArray)
        {
            for (int i = bitArray.Length - 1; i >= 0; i--)
            {
                if (bitArray[i])
                {
                    return i + 1;
                }
            }

            return 0;
        }

        /// <summary>
        /// The result is true if and only if the argument is not null and is a Bitset object that has exactly the same set of bits set to true as this bit set. That is, for every nonnegative int index k,
        /// ((BitSet)obj).get(k) == this.get(k)
        /// </summary>
        /// <param name="bitArray1"></param>
        /// <param name="bitArray2"></param>
        /// <returns></returns>
        public static bool IsEquals(this BitArray bitArray1, BitArray bitArray2)
        {
            if (bitArray2 == null || bitArray1.Length != bitArray2.Length)
                return false;
            for (int i = 0; i < bitArray1.Length; i++)
            {
                if (bitArray1.Get(i) != bitArray2.Get(i))
                    return false;
            }
            return true;
        }
    }
}

